package com.ak.server.quartz.controller;

import java.util.Map;

import org.quartz.SchedulerException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ak.common.controller.BaseController;
import com.ak.common.entity.AKResponse;
import com.ak.common.entity.QueryRequest;
import com.ak.common.utils.AKUtil;
import com.ak.server.quartz.entity.SysJob;
import com.ak.server.quartz.exception.TaskException;
import com.ak.server.quartz.service.ISysJobService;

import lombok.RequiredArgsConstructor;

/**
 * 调度任务信息操作处理
 *
 * @author Vean
 */
@RestController
@RequestMapping("job")
@RequiredArgsConstructor
public class SysJobController extends BaseController {

    private final ISysJobService jobService;

    @GetMapping
    public AKResponse list(QueryRequest request, SysJob job) {
        Map<String, Object> dataTable = AKUtil.getDataTable(jobService.selectJobList(job, request));
        return new AKResponse().data(dataTable);
    }
    
    /**
     * 新增保存调度
     */
    @PostMapping
    public boolean add(@Validated SysJob job) throws SchedulerException, TaskException {
        return jobService.insertJob(job) > 0 ? true : false;
    }

    /**
     * 修改保存调度
     */
    @PutMapping
    public boolean update(@Validated SysJob job) throws SchedulerException, TaskException {
        return jobService.updateJob(job) > 0 ? true : false;
    }

    @DeleteMapping("/{ids}")
    public void remove(@PathVariable("ids") String ids) throws SchedulerException {
        jobService.deleteJobByIds(ids);
    }

    /**
     * 任务调度状态修改
     */
    @PutMapping("/changeStatus")
    public boolean changeStatus(SysJob job) throws SchedulerException {
        SysJob newJob = jobService.selectJobById(job.getJobId());
        newJob.setStatus(job.getStatus());
        return jobService.changeStatus(newJob) > 0 ? true : false;
    }

    /**
     * 任务调度立即执行一次
     */
    @PostMapping("/run")
    public void run(SysJob job) throws SchedulerException {
        jobService.run(job);
    }

    /**
     * 校验cron表达式是否有效
     */
    @PostMapping("/checkCronExpressionIsValid")
    public boolean checkCronExpressionIsValid(SysJob job) {
        return jobService.checkCronExpressionIsValid(job.getCronExpression());
    }
}
